home *** CD-ROM | disk | FTP | other *** search
- Path: altair.dur.ac.uk!d51qvn
- From: P D Johnson <P.D.Johnson@durham.ac.uk>
- Newsgroups: comp.lang.c
- Subject: Re: RETURN ();
- Date: 9 Feb 1996 00:32:07 GMT
- Organization: University of Durham, Durham, UK.
- Message-ID: <4fe4m7$53m@mercury.dur.ac.uk>
- References: <DMFxxq.7M7@emi.net>
- NNTP-Posting-Host: altair.dur.ac.uk
- X-Newsreader: TIN [version 1.2 PL2]
-
- samstar@emi.net wrote:
- : Is there a way to return muliple values to main from a seperate function ?
-
- : ex :
-
- : int main(void)
- : {
- : Input_data();
- : printf("Here all the input data");
- :
- : return 0;
- : }
-
- : int Input_data()
- : {
- : x=5,y=30,z=10 /* These were gotten by asking questions */
- : /* using printf / scanf/fgets (what ever) */
- : /*point is they are gotten by question */
-
- : return(x,y,z);
- : }
-
- : how will main be able to see these values ?
-
- : I tried this in main didn't help :
-
- : int main(x,y,z)
- : {
- : ect...
- : }
-
- : if anyone can help... please email me at samstar@emi.net
-
-
- : thanks....
-
- : samstar
-
-
- No, NO, NO, NO, NO ........
-
- Have you tried reading a book on C? You seem to have a lack of
- understanding of how variables work in C. You can not even start to write
- a program to do this until you have sorted out the basics of variables
- and variable scope.
-
- Basically in C you declare a variable with a line like
-
- int x;
-
- You can now write code like x=10; x=5; but only in the function were you
- declared the variable. What you want to do is pass back values from one
- function to another. First of all, for one value this is easy as functions
- can return A value. ie
-
- int main(void)
- {
- int x;
-
- x = get_input();
- printf("%d", x);
- }
-
- int get_input()
- {
- return(10);
- }
-
- In your program you want to return several values. you can not use
- return(x,y,z) as you cannot write x,y,z = get_input() in main() it makes
- no sense to a C compiler(you might know what you mean).
-
- The proper way to do this is to use variable addresses and pointers to
- variables, I have not got time to explain these but any good C book will
- take you through it. There is another way of doing things which for small
- programs you may find a helpfull. You can define a variable outside a
- function. This is called making a variable global ie all functions after
- its declaration can see it. This code may make it more obvious.
-
- /* ---- Global variables --- */
- int x,y,z;
- /* ------------------------- */
-
- int main(void)
- {
- get_values();
- printf("%d %d %d",x,y,z);
- }
-
- void get_values(void)
- {
- x=10;
- y=10;
- z=10;
- /* No need to return values as we are using the variables declared at
- the top of the program */
- }
-
- A book will take you a long way, if you have already got one then by the
- looks of things get another one, try your library.
-
- Paul.
-